﻿using SimplePersonManager.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SimplePersonManager.WebAPI.Controllers
{
    public class PersonController : ApiController
    {
        SimplePersonManager _simplePersonManager = new SimplePersonManager();

        // GET api/person
        public IEnumerable<Person> Get()
        {
            try
            {
                var people = _simplePersonManager.GetPeople();
                return people;
            }
            catch (Exception)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }

        // GET api/person/name
        public Person Get(string id)
        {
            try
            {
                var person = _simplePersonManager.GetPersonByName(id);
                if (person != null)
                    return person;

                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            catch (Exception)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }

        // POST api/person
        public HttpResponseMessage Post([FromBody]Person person)
        {
            try
            {
                if (ModelState.IsValid && person != null)
                {
                    _simplePersonManager.SavePerson(person);

                    var response = new HttpResponseMessage(HttpStatusCode.Created);

                    response.Headers.Location = GetPersonLocation(person.Name);

                    return response;
                }

                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            catch (DuplicatePersonException)
            {
                var responseMessage = new HttpResponseMessage(HttpStatusCode.Conflict);
                responseMessage.Content = new StringContent(
                    string.Format("Trying to store a Person with name '{0}', which is already present in the store.", person.Name));

                throw new HttpResponseException(responseMessage);
            }
            catch (Exception)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }

        private Uri GetPersonLocation(string personName)
        {
            string uri = Url.Route("DefaultApi", new { id = personName });
            return new Uri(Request.RequestUri, uri);
        }

        //// PUT api/person/5
        //public void Put(int id, [FromBody]string value)
        //{
        //}

        //// DELETE api/person/5
        //public void Delete(int id)
        //{
        //}
    }
}
